"""
用户模型
创建时间：2025-09-12
作者：开发团队
目的：定义用户数据模型
"""

from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from ..core.database import Base



class User(Base):
    """用户模型"""
    
    __tablename__ = "users"
    
    # 基础字段
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    password_hash = Column(String(255), nullable=False)
    name = Column(String(100), nullable=False)
    role = Column(String(20), nullable=False)  # guard, admin, superadmin
    phone = Column(String(20))
    campus_id = Column(Integer, ForeignKey("campuses.id"))
    status = Column(String(20), default="active")
    last_login = Column(DateTime)
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
    
    # 关系
    campus = relationship("Campus", back_populates="users")
    verification_records = relationship("VerificationRecord", back_populates="guard")
    keys = relationship("Key", back_populates="creator")
    audit_logs = relationship("AuditLog", back_populates="user")
    data_packages = relationship("DataPackage", back_populates="creator")
    
    def __repr__(self):
        return f"<User(id={self.id}, username='{self.username}', role='{self.role}')>"